import CryptoJS from 'crypto-js';

export default class AES {
  /**
   * 获取长度为16的随机字符串，用以上传后台进行加密同时用以前端解密
   */
  public static getAesEncryptKey(): string {
    const keyLength = 16;
    const baseString =
      'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    const arr: string[] = [];

    for (let i = 0; i < keyLength; i++) {
      const idx = Math.floor(Math.random() * baseString.length);
      arr.push(baseString[idx]);
    }
    return arr.join('');
  }

  /**
   * aes加密
   */
  public static aesEncrypt(text: string, aesKey: string): string {
    const key = CryptoJS.enc.Latin1.parse(aesKey);
    return CryptoJS.AES.encrypt(text, key, {
      mode: CryptoJS.mode.ECB,
    }).toString();
  }

  /**
   * aes解密
   */
  public static aesDecrypt(
    text: string,
    aesKey: string,
    aesIv: string,
  ): string {
    const key = CryptoJS.enc.Latin1.parse(aesKey);
    const iv = CryptoJS.enc.Latin1.parse(aesIv);
    return CryptoJS.AES.decrypt(text, key, {iv, mode: CryptoJS.mode.CBC})
      .toString()
      .split(/(.{2})/)
      .filter(s => s.length === 2)
      .map(s => parseInt(s, 16))
      .map(n => String.fromCharCode(n))
      .join('');
  }
}
